﻿#include "ServerUdpMonitor.h"
#include "global.h"
#include <QJsonDocument>
#include <QJsonParseError>
ServerUdpMonitor::ServerUdpMonitor(QObject *parent) : QObject(parent)
{
    //emit sig_ShowMessage(UT("开始监听UDP消息"));

}

ServerUdpMonitor::~ServerUdpMonitor()
{
    if(pUDPListener != nullptr)
    {
        delete pUDPListener;
        pUDPListener = nullptr;
    }

}

ServerUdpMonitor::ServerUdpMonitor(QHostAddress LocalAddr, int LocalPort)
{
    // 配置UDP
    pUDPListener = new QUdpSocket(this);
    // 绑定本机的UDP的端口和IP地址
    pUDPListener->bind(LocalAddr, LocalPort);

    // 连接信号和槽函数
    connect(pUDPListener, SIGNAL(readyRead()), this, SLOT(slot_ReceiveDataFromServer()));
}

/*
 * @brief  接收服务器的数据
 * @param
 * @return
 */
void ServerUdpMonitor::slot_ReceiveDataFromServer()
{
    // 判断UDP端口是否有待接收的数据
    while(pUDPListener->hasPendingDatagrams())
    {
        QByteArray dataRead;

        dataRead.resize(pUDPListener->pendingDatagramSize());           //  把dataRead的大小设为收到的JSON数据的大小
        pUDPListener->readDatagram(dataRead.data(), dataRead.size());   //  把从UDP读取到的数据存储到dataRead
        mylog<<dataRead;
        QJsonParseError error;
        QJsonObject json_data = QJsonDocument::fromJson(dataRead,&error).object();

        if(error.error == QJsonParseError::NoError)               //  转换成功并且收到的数据非空
        {
            mylog<<json_data;
            emit sig_ServerCommandReady(json_data);   //  发送给DispatchCore处理
        }
        else
        {
            mylog<<error.errorString();
        }
    }
}
